package com.siyoumi.app.modules.money.service;

import com.siyoumi.app.entity.*;
import com.siyoumi.app.modules.fun.service.SvcFun;
import com.siyoumi.app.modules.prize.service.SvcSysPrize;
import com.siyoumi.app.modules.prize.service.SvcSysPrizeSet;
import com.siyoumi.app.sys.service.IPayOrder;
import com.siyoumi.app.sys.service.payorder.PayOrder;
import com.siyoumi.app.sys.service.prize.PrizeSend;
import com.siyoumi.app.service.*;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.InputData;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

//钱包
@Slf4j
public class PayOrderMoney
        implements IPayOrder {

    protected IPayOrder getPayOrder() {
        return PayOrder.getBean(getEntity());
    }

    //下单
    static public XReturn order(String uid, String id, BigDecimal payPrice) {
        PayOrder.payExpireHandleByOpenid(uid, "money");

        SysAbc entityAbc = SysAbcService.getBean().getEntityByTable(id, "money_option");
        if (entityAbc == null) {
            return EnumSys.ERR_VAL.getR("充值项不存在");
        }

        BigDecimal orderPrice = entityAbc.getAbc_num_00();
        //if (entityAbc.getAbc_int_01() == 1) {
        //    log.info("自定义金额，开发者控制");
        //    orderPrice = payPrice;
        //}
        if (orderPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return XReturn.getR(20054, "充值项金额异常");
        }

        LocalDateTime expireDate = XDate.now().plusMinutes(10);
        SysOrder entityOrder = SysOrderService.getBean().newEntity("money", uid
                , expireDate
                , orderPrice
                , entityAbc.getAbc_name()
                , 0
                , entityAbc.getAbc_id());

        XReturn r = XReturn.getR(0);
        r.setData("entity_order", entityOrder);
        return r;
    }

    @Override
    public XReturn pay(String code) {
        return getPayOrder().pay(code);
    }

    @Override
    public XReturn payChoose(String code) {
        return null;
    }

    @Override
    public XReturn payCheck() {
        XReturn r = getPayOrder().payCheck();
        if (r.err()) {
            return r;
        }

        XApp.getTransaction().execute(status -> {
            SysAbcService appAbc = SysAbcService.getBean();
            SysAbc entityAbc = appAbc.loadEntity(getEntity().getOrder_id_00());
            BigDecimal addMoney = entityAbc.getAbc_num_00();
            if (entityAbc.getAbc_int_01() == 1) {
                //自定义充值（金额客户端决定）
                addMoney = getEntity().getOrder_pay_price();
            }

            log.info("充值金额");
            SvcMoneyRecord svcMoneyRecord = SvcMoneyRecord.getBean();
            svcMoneyRecord.add(getEntity().getOrder_id()
                    , getEntity().getOrder_uid()
                    , getEntity().getOrder_id()
                    , getEntity().getOrder_app_id()
                    , addMoney
                    , "充值");
            if (entityAbc.getAbc_num_01().compareTo(new BigDecimal("0")) > 0) {
                log.info("充值赠送金额");

                svcMoneyRecord.add("append|" + getEntity().getOrder_id()
                        , getEntity().getOrder_uid()
                        , getEntity().getOrder_id()
                        , getEntity().getOrder_app_id()
                        , entityAbc.getAbc_num_01()
                        , "充值赠送");
            }
            if (entityAbc.getAbc_int_00() > 0) {
                log.info("充值赠送积分");
                SvcFun.getBean().add(getEntity().getOrder_id()
                        , getEntity().getOrder_uid()
                        , getEntity().getOrder_id()
                        , getEntity().getOrder_app_id()
                        , entityAbc.getAbc_int_00()
                        , "充值赠送");
            }

            log.info("充值赠送礼品");
            SvcSysPrizeSet svcSysPrizeSet = SvcSysPrizeSet.getBean();
            InputData inputData = InputData.getIns();
            inputData.put("id_src", entityAbc.getAbc_str_00());
            JoinWrapperPlus<SysPrizeSet> queryPrizeSet = svcSysPrizeSet.listQuery(inputData);
            List<SysPrizeSet> listPrizeSet = SvcSysPrizeSet.getApp().get(queryPrizeSet);
            for (SysPrizeSet entityPrizeSet : listPrizeSet) {
                PrizeSend ps = PrizeSend.getBean(entityPrizeSet);

                log.info("充值赠送礼品-奖品：{}", entityPrizeSet.getPset_name());
                String key = XStr.concat(getEntity().getOrder_id(), "|", entityPrizeSet.getKey());
                ps.send(key, getEntity().getOrder_uid());
            }

            return true;
        });


        return r;
    }

    @Override
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn rollback() {
        return XReturn.getR(20100, "钱包订单无法回滚");
    }


    @Override
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn cancel() {
        return XReturn.getR(20100, "钱包订单无法取消");
    }

    @Override
    public XReturn refundApply(String refundId, BigDecimal refundPrice, String desc) {
        return getPayOrder().refundApply(refundId, refundPrice, desc);
    }

    @Override
    public XReturn refund(String refundId) {
        XReturn r = getPayOrder().refund(refundId);
        if (r.err()) {
            //退款失败
            return r;
        }

        SvcMoneyRecord svcMoneyRecord = SvcMoneyRecord.getBean();

        XApp.getTransaction().execute(status -> {
            SysMoneyRecord entityRecord = svcMoneyRecord.getEntityByKey(getEntity().getOrder_id());
            SysMoneyRecord entityRecordAppend = svcMoneyRecord.getEntityByKey("append|" + getEntity().getOrder_id());

            BigDecimal moneyTotal = entityRecord.getMrec_num();
            if (entityRecordAppend != null) {
                moneyTotal = moneyTotal.add(entityRecordAppend.getMrec_num());
            }
            log.info("退充值金额和赠送金额：{}", moneyTotal);

            String key = "refund|" + getEntity().getOrder_id();
            svcMoneyRecord.add(key
                    , getEntity().getOrder_uid()
                    , getEntity().getOrder_id()
                    , getEntity().getOrder_app_id()
                    , moneyTotal
                    , "退款");

            FunRecord entityFun = SvcFun.getBean().getEntityByKey(getEntity().getOrder_id());
            if (entityFun != null) {
                log.info("删除积分");
                SvcFun.getApp().removeById(entityFun);
                SvcFun.getBean().updateFun(getEntity().getOrder_uid());
            }

            log.info("删除奖品");
            SvcSysPrize.getApp().update()
                    .set("prize_del", XDate.toS())
                    .eq("prize_app_id", "money")
                    .likeRight("prize_key", getEntity().getOrder_id() + "|")
                    .update();

            return true;
        });


        return r;
    }
}
